export default {
	namespaced: true,
	state: () => ({
		//购物车中的商品 {goods_id, goods_count, goods_name, goods_price, goods_small_logo, goods_state}
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'), 
	}),
	mutations: {
		//商品加入购物车
		addToCart(state, goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id);
			
			if(!findResult){
				//购物车中没有这件商品
				state.cart.push(goods);
			}else{
				//购物车中有这件商品
				findResult.goods_count++;
			}
			
			this.commit('m_cart/saveToStorage');
		},
		//把购物车的商品数据进行持久化存储
		saveToStorage(state){
			uni.setStorageSync('cart', JSON.stringify(state.cart));
		},
		//修改商品状态
		updateGoodsState(state, goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id);
			
			if(findResult){
				//找到该商品
				findResult.goods_state = goods.goods_state;
				this.commit('m_cart/saveToStorage');
			}
		},
		//修改商品数量
		updateGoodsCount(state, goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id);
			
			if(findResult){
				//找到该商品
				findResult.goods_count = goods.goods_count;
				this.commit('m_cart/saveToStorage');
			}
		},
		//根据 id 删除商品
		removeGoodsById(state, goods_id){
			state.cart = state.cart.filter(x => x.goods_id !== goods_id);
			this.commit('m_cart/saveToStorage');
		},
		//修改全部商品的选中状态
		updateAllGoodsState(state, newState){
			state.cart.forEach(x => {
				x.goods_state = newState;
			});
			
			this.commit('m_cart/saveToStorage');
		},
	},
	getters: {
		//统计商品总数
		total(state){
			/* let c = 0;
			
			state.cart.forEach(x => c += x.goods_count);
			return c; */
			
			const sum = state.cart.reduce((total, item) => total += item.goods_count, 0);
			
			return sum;
		},
		//统计选中商品数量
		checkedCount(state){
			return state.cart.filter(x => x.goods_state).reduce((total, item) => {
				return total += item.goods_count;
			}, 0);
		},
		//统计选中商品的总价
		checkedTotalPrice(state){
			return state.cart.filter(x => x.goods_state).reduce((total, item) => {
				return total += item.goods_count * item.goods_price;
			}, 0).toFixed(2);
		},
	},
}